import React, { Component } from 'react'
import { connect } from 'dva';

import { Form, Input, Cascader, message, Button } from 'antd';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';

import { LOCATION, DICT, TYPE } from '../enum';
import { firstUpperCase } from '@/utils/util';
import Link from 'umi/link';

interface Props {
  current: number;
  form: any;
  loading?: boolean;
  dispatch?: Function;
  initCurrent: Function;
  location?: Array<any>;
  type?: Array<any>;
  dict?: object;
  cond?: any;
  file?: {
    message: string;
    url: string;
  };
}

const FormItem = Form.Item;

@connect(({ fire_facilities, upload, loading }) => ({
  location: fire_facilities.location || [],
  type: fire_facilities.type || [],
  cond: fire_facilities.cond || {},
  dict: fire_facilities.dict || {},
  file: upload.fileValue || {},
}))
class Search extends Component<Props, any> {

  state = {
    option: [],
    isDisabled: true
  };

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'fire_facilities/init',
      payload: {
        dict: { keyList: DICT }
      }
    })
  }

  loadData = (type, selectedOptions) => {
    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `fire_facilities/query${firstUpperCase(type)}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  private handleSelect = (type, v) => {
    const { cond = {}, dispatch } = this.props;

    const ans = v[v.length - 1] ? v[v.length - 1].split('%%')[0] : null;
    const payload = {
      ...cond,
      ...(type === 'location' ? {
        floorId: null,
        areaId: null,
        buildId: null,
        ...(LOCATION[v.length - 1] ? { [`${LOCATION[v.length - 1].type}Id`]: ans } : {})
      } : {
          deviceType: null,
          fire: null,
          ...(v && v[0] ? { fire: v[0].split('%%')[0] } : {}),
          ...(v && v[1] ? { deviceType: v[1].split('%%')[0] } : {}),
        })
    }

    dispatch({
      type: 'fire_facilities/updateCond',
      payload,
    })
  }

  private search = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.props.form.validateFields((err: undefined | {}, values: any) => {
      if (!err) {
        const ans1 = Array.isArray(values.buildList) && values.buildList[values.buildList.length - 1]
          ? values.buildList[values.buildList.length - 1].split('%%')[0]
          : null;
        const ans2 = Array.isArray(values.typeList) && values.typeList[values.typeList.length - 1]
          ? values.typeList[values.typeList.length - 1].split('%%')[0]
          : null;
        dispatch({
          type: 'fire_facilities/updateCond',
          payload: {
            ...values,
            ...(Array.isArray(values.buildList) && LOCATION[values.buildList.length - 1]
              ? { [`${LOCATION[values.buildList.length - 1].type}Id`]: ans1 }
              : {}),
            ...(Array.isArray(values.typeList) && TYPE[values.typeList.length - 1]
              ? { [`${TYPE[values.buildList.length - 1].type}Id`]: ans2 }
              : {}),
          }
        });
        this.props.initCurrent()
      }
    });
  };

  showUpload = (v) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'fire_facilities/queryTemple',
      payload: {
        type: 'fire_facilities',
      }
    })
  }

  render() {
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
    };
    return (
      <Form onSubmit={this.search}>
        <SearchRow>
          <SearchCol key={0} span={5}>
            <FormItem
              label="名称"
              {...formItemLayout}
            >
              {getFieldDecorator('name', {
                rules: [{ message: '名称' }],
              })(
                <Input placeholder="请选择名称" allowClear />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={1} span={5}>
            <Form.Item
              {...formItemLayout}
              label='所在位置'
            >
              {getFieldDecorator('buildList', {
                rules: [{ required: false, message: '所在建筑' }],
              })(
                <Cascader
                  options={this.props.location}
                  loadData={this.loadData.bind(this, 'location')}
                  changeOnSelect
                  onChange={this.handleSelect.bind(this, 'location')}
                  placeholder="请选择"
                />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol key={2} span={5}>
            <FormItem
              label="类型"
              {...formItemLayout}
            >
              {getFieldDecorator('typeList', {
                rules: [{ required: false, message: '器材类型' }],
              })(
                <Cascader
                  options={this.props.type}
                  loadData={this.loadData.bind(this, 'type')}
                  changeOnSelect
                  onChange={this.handleSelect.bind(this, 'type')}
                  placeholder="请选择"
                />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={4} span={9}>
            <SearchRow type="flex" justify="end" style={{ height: '65px' }}>
              <SearchButton icon="redo" onClick={(e) => {
                this.props.form.resetFields();
                this.search(e)
              }} >重置</SearchButton>
              <SearchButton icon="search" htmlType="submit">搜索</SearchButton>
              <SearchButton icon="select" style={{ marginLeft: '10px' }} onClick={this.showUpload}>导入</SearchButton>
              <Link to='/data/facilities/new'>
                <SearchButton icon='plus' type="primary">新增</SearchButton>
              </Link>
            </SearchRow>
          </SearchCol>
        </SearchRow>
      </Form>
    );
  }
}

const SearchS = Form.create<Props>()(Search);
export default SearchS;
